/*******************************************************************************
 *                                    ZLG
 *                         ----------------------------
 *                         innovating embedded platform
 *
 * Copyright (c) 2001-present Guangzhou ZHIYUAN Electronics Co., Ltd.
 * All rights reserved.
 *
 * Contact information:
 * web site:    https://www.zlg.cn
 *******************************************************************************/
/*******************************************************************************
 * Includes
 ******************************************************************************/
#include <stdio.h>
#include "core/include/hc32f4a0_clk.h"
#include "common/hc32f4a0_errno.h"
#include "armv7m/armv7_core_m4.h"

/*******************************************************************************
 * Static
 ******************************************************************************/
static uint32_t          tick_step  = 0;
static volatile uint32_t tick_count = 0;

/*******************************************************************************
 * Code
 ******************************************************************************/
/**
 * \brief 毫秒级延时函数
 */
void delay_ms(uint32_t cnt){
    volatile uint32_t i;
    const uint32_t cyc = sys_clk_hclk_get() / 10000;

    while (cnt-- > 0UL) {
        i = cyc;
        while (i-- > 0) {
            ;
        }
    }
}

/**
 * \brief system tick 计数
 */
__attribute__((weak)) void systick_inc(void){
    tick_count += tick_step;
}

/**
 * \brief System tick中断处理函数
 */
__attribute__((weak)) void SysTick_Handler(void){
    systick_inc();
}

/**
 * \brief 初始化 system tick
 */
__attribute__((weak)) int sys_tick_init(uint32_t freq){
    int Ret = -EPERM;

    if ((0 != freq) && (freq <= 1000)) {
        tick_step = 1000 / freq;
        /* 配置system tick中断*/
        if (0UL == systick_config(sys_clk_hclk_get() / freq)) {
            Ret = 0;
        }
    }

    return Ret;
}

